from decimal import Decimal
from django.utils import timezone
from django.db import transaction
from .models import DriverAccount, TransactionRecord
from login.models import User
import logging

logger = logging.getLogger(__name__)

class PaymentService:
    """支付相关服务"""
    
    @staticmethod
    def ensure_user_account(user_id, user_type=0):
        """
        确保用户账户存在，如果不存在则创建
        user_type: 0-乘客, 1-司机
        """
        try:
            # 检查用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                logger.error(f"用户不存在: {user_id}")
                return False, "用户不存在"
            
            # 如果是司机，确保司机账户存在
            if user_type == 1:
                driver_account, created = DriverAccount.objects.get_or_create(
                    driver_id=user,
                    defaults={
                        'balance': Decimal('0.00'),
                        'frozen_amount': Decimal('0.00'),
                        'status': 1
                    }
                )
                
                if created:
                    logger.info(f"为司机 {user_id} 创建了新的账户")
                    return True, "司机账户创建成功"
                else:
                    logger.info(f"司机 {user_id} 账户已存在")
                    return True, "司机账户已存在"
            
            # 如果是乘客，目前乘客不需要账户，但可以在这里添加乘客相关的逻辑
            else:
                logger.info(f"乘客 {user_id} 账户检查完成")
                return True, "乘客账户检查完成"
                
        except Exception as e:
            logger.error(f"确保用户账户失败: {str(e)}")
            return False, str(e)
    
    @staticmethod
    def process_order_payment(order):
        """
        处理订单支付成功后的逻辑
        - 确保乘客和司机账户存在
        - 将订单金额添加到司机余额
        - 创建交易记录
        """
        if not order.driver_id:
            logger.warning(f"订单 {order.order_number} 没有司机，跳过余额处理")
            return
        
        try:
            with transaction.atomic():
                # 确保乘客账户存在
                passenger_success, passenger_msg = PaymentService.ensure_user_account(
                    order.passenger_id, user_type=0
                )
                if not passenger_success:
                    logger.error(f"乘客账户处理失败: {passenger_msg}")
                    return False
                
                # 确保司机账户存在
                driver_success, driver_msg = PaymentService.ensure_user_account(
                    order.driver_id, user_type=1
                )
                if not driver_success:
                    logger.error(f"司机账户处理失败: {driver_msg}")
                    return False
                
                # 获取司机用户对象
                try:
                    driver = User.objects.get(id=order.driver_id)
                except User.DoesNotExist:
                    logger.error(f"司机不存在: {order.driver_id}")
                    return False
                
                # 计算总支付金额（订单金额 + 额外费用）
                total_amount = PaymentService._calculate_total_amount(order)
                
                # 获取司机账户（此时应该已经存在）
                try:
                    driver_account = DriverAccount.objects.get(driver_id=driver)
                except DriverAccount.DoesNotExist:
                    logger.error(f"司机账户不存在: {order.driver_id}")
                    return False
                
                # 更新司机余额
                old_balance = driver_account.balance
                driver_account.balance += total_amount
                driver_account.save()
                
                # 创建交易记录
                transaction_record = TransactionRecord.objects.create(
                    driver_id=driver,
                    order_id=order.id,
                    transaction_type=0,  # 收入
                    amount=total_amount,
                    balance=driver_account.balance,
                    transaction_time=timezone.now(),
                    remark=f"订单收入 - {order.order_number}"
                )
                
                logger.info(f"订单 {order.order_number} 支付处理成功:")
                logger.info(f"  乘客ID: {order.passenger_id}")
                logger.info(f"  司机ID: {order.driver_id}")
                logger.info(f"  订单金额: {total_amount}")
                logger.info(f"  原余额: {old_balance}")
                logger.info(f"  新余额: {driver_account.balance}")
                logger.info(f"  交易记录ID: {transaction_record.id}")
                
                return True
                
        except Exception as e:
            logger.error(f"处理订单支付失败: {str(e)}")
            import traceback
            logger.error(f"异常堆栈: {traceback.format_exc()}")
            return False
    
    @staticmethod
    def _calculate_total_amount(order):
        """计算订单总金额（包含额外费用）"""
        from order.models import OrderExtraFee
        
        # 获取额外费用
        extra_fees = OrderExtraFee.objects.filter(order=order)
        total_extra_amount = sum(fee.amount for fee in extra_fees)
        
        # 总金额 = 订单基础金额 + 额外费用
        total_amount = order.order_amount + total_extra_amount
        
        logger.info(f"订单 {order.order_number} 金额计算:")
        logger.info(f"  基础金额: {order.order_amount}")
        logger.info(f"  额外费用: {total_extra_amount}")
        logger.info(f"  总金额: {total_amount}")
        
        return total_amount
    
    @staticmethod
    def add_driver_balance(driver_id, amount, remark="余额充值", order_id=None):
        """
        为司机添加余额的通用方法
        """
        try:
            with transaction.atomic():
                # 确保司机账户存在
                driver_success, driver_msg = PaymentService.ensure_user_account(driver_id, user_type=1)
                if not driver_success:
                    logger.error(f"司机账户处理失败: {driver_msg}")
                    return False, driver_msg
                
                # 获取司机用户对象
                try:
                    driver = User.objects.get(id=driver_id)
                except User.DoesNotExist:
                    logger.error(f"司机不存在: {driver_id}")
                    return False, "司机不存在"
                
                # 验证金额
                if amount <= 0:
                    return False, "金额必须大于0"
                
                amount = Decimal(str(amount))
                
                # 获取司机账户（此时应该已经存在）
                try:
                    driver_account = DriverAccount.objects.get(driver_id=driver)
                except DriverAccount.DoesNotExist:
                    logger.error(f"司机账户不存在: {driver_id}")
                    return False, "司机账户不存在"
                
                # 更新余额
                old_balance = driver_account.balance
                driver_account.balance += amount
                driver_account.save()
                
                # 创建交易记录
                transaction_record = TransactionRecord.objects.create(
                    driver_id=driver,
                    order_id=order_id,
                    transaction_type=0,  # 收入
                    amount=amount,
                    balance=driver_account.balance,
                    transaction_time=timezone.now(),
                    remark=remark
                )
                
                logger.info(f"司机 {driver_id} 余额增加成功: +{amount}, 新余额: {driver_account.balance}")
                
                return True, {
                    "old_balance": float(old_balance),
                    "new_balance": float(driver_account.balance),
                    "added_amount": float(amount),
                    "transaction_id": transaction_record.id
                }
                
        except Exception as e:
            logger.error(f"添加司机余额失败: {str(e)}")
            return False, str(e)

    @staticmethod
    def handle_payment_success(order_number):
        """
        处理支付成功后的完整逻辑
        - 确保乘客和司机账户存在
        - 更新订单状态
        - 处理司机余额
        """
        from order.models import Order, OrderStatusLog
        
        try:
            with transaction.atomic():
                # 获取订单
                try:
                    order = Order.objects.get(order_number=order_number)
                except Order.DoesNotExist:
                    logger.error(f"订单不存在: {order_number}")
                    return False, "订单不存在"
                
                # 检查订单状态，避免重复处理
                if order.order_status == 4:
                    logger.info(f"订单 {order_number} 已支付，跳过处理")
                    return True, "订单已支付"
                
                # 确保乘客账户存在
                passenger_success, passenger_msg = PaymentService.ensure_user_account(
                    order.passenger_id, user_type=0
                )
                if not passenger_success:
                    logger.error(f"乘客账户处理失败: {passenger_msg}")
                    return False, passenger_msg
                
                # 确保司机账户存在
                if order.driver_id:
                    driver_success, driver_msg = PaymentService.ensure_user_account(
                        order.driver_id, user_type=1
                    )
                    if not driver_success:
                        logger.error(f"司机账户处理失败: {driver_msg}")
                        return False, driver_msg
                
                # 更新订单状态
                order.order_status = 4  # 4=已支付
                order.save()
                
                # 记录状态变更日志
                OrderStatusLog.objects.create(
                    order=order,
                    status=4,
                    operator_type=0,  # 0-系统
                    operator_id=0,    # 系统操作，使用0作为ID
                    create_time=timezone.now(),
                    remark="支付成功"
                )
                
                # 如果订单有司机，处理司机余额
                if order.driver_id:
                    success = PaymentService.process_order_payment(order)
                    if not success:
                        logger.error(f"司机余额处理失败: {order_number}")
                        return False, "司机余额处理失败"
                
                logger.info(f"支付成功处理完成: {order_number}")
                return True, "支付成功处理完成"
                
        except Exception as e:
            logger.error(f"处理支付成功失败: {str(e)}")
            import traceback
            logger.error(f"异常堆栈: {traceback.format_exc()}")
            return False, str(e)
